package Logic;

import irio.gamer.gamer;

import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream.GetField;
import java.util.ArrayList;

import utils.Util;
import utils.Vec;

public class Movie {

	
	public static boolean isFilming = false;
	
	public class MovieParam {
		public Vec camera = new Vec();
		public Vec target = new Vec();
		public Vec up = new Vec();
		public int steps = 0;
		public MovieParam(Vec c, Vec t, Vec u, int s) {
			camera.set(c);
			target.set(t);
			up.set(u);
			steps = s;
		}
	}
	
	private int currentFrame = 0;
	private int currentPosition = 0;
	
	public ArrayList<MovieParam> movieParams = new ArrayList<MovieParam>();
	
	public void AddCurrent(int steps) {
		movieParams.add(new MovieParam(gamer.rp.camera, gamer.rp.target, gamer.rp.up, steps));
	}

	public String getCurrentFilename() {
		return gamer.gamerParams.movieDir + "frame" + String.format("%05d", currentFrame) + ".bmp";
	}
	
	public void StartRendering() {
		currentFrame = 0;
		currentPosition = 0;
		File dir = new File(gamer.gamerParams.movieDir);
		for(File file: dir.listFiles()) 
			file.delete();

		boolean done = false;
		while (!done) {
			done = RenderStep();
		}
	
	
	}
	
	private boolean RenderStep() {
		int sumFrame = 0;
		int localFrame = 0;
		for (int i=0;i<movieParams.size();i++) {
			MovieParam a = movieParams.get(i);
			if (currentFrame >= sumFrame &&  currentFrame< a.steps + sumFrame) {
				localFrame = currentFrame - sumFrame;
				currentPosition = i;
			}
			sumFrame+= a.steps;
		}
		// end
		if (currentPosition == movieParams.size()-1)
			return true;
		
		MovieParam a = movieParams.get(currentPosition);
		MovieParam b = movieParams.get(currentPosition+1);
		double val = localFrame / (double)a.steps;
		gamer.rp.camera.interpolate(a.camera, b.camera, val);
		gamer.rp.target.interpolate(a.target, b.target, val);
		gamer.rp.up.interpolate(a.up, b.up, val);

		
		System.out.println("Current step: " + currentFrame + " local: " + localFrame + "   " + gamer.rp.camera.toString());

		boolean done = false;
		while (!done) {
			done = gamer.executeGamer(false);
		}
		
		while (GamerParams.isRendering) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	//	Process p = Runtime.getRuntime().exec("cp ");
		try {
			Thread.sleep(500);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			Util.copyFile(new File("output/image.bmp"), new File(getCurrentFilename()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		currentFrame++;
		
		
		
		return false;
		
	}
	
	
}
